//
//  WXSpeech.m
//  YouYiKuProject
//
//  Created by xue on 2018/12/27.
//  Copyright © 2018年 xuezi. All rights reserved.
//

#import "WXSpeech.h"
#import <AVFoundation/AVFoundation.h>
#import "WXVoiceSDK.h"

#define DEFINE_SHARED_INSTANCE_USING_BLOCK(block) \
static dispatch_once_t pred = 0; \
static id _sharedObject = nil; \
dispatch_once(&pred, ^{ \
_sharedObject = block(); \
}); \
return _sharedObject; \


@interface WXSpeech ()<WXVoiceDelegate>

@property (nonatomic,strong) NSString *rsultStr;
@end

@implementation WXSpeech

+ (WXSpeech *)sharedInstance{
    
    DEFINE_SHARED_INSTANCE_USING_BLOCK(^{
        
        return [[self alloc] init];
    });
}

- (id)init{
    
    self = [super init];
    if (self) {
        [self initRecognizer];
    }
    return self;
}

#pragma mark -----------WXVoiceDelegate------------

// 调用我们的引擎之后可能收到的一些有用和错误信息都在下面的回调当中返回！！！！！！！！！！！！！！！！！！！！！！！！
- (void)voiceInputResultArray:(NSArray *)array{
    //一旦此方法被回调，array一定会有一个值，所以else的情况不会发生，但写了会更有安全感的
    NSLog(@"-------------call back voiceInputResultArray%@----------------",array);
    if (array && array.count>0) {
        WXVoiceResult *result=[array objectAtIndex:0];
        NSLog(@"语音识别结果=%@",result.text);
        
        self.rsultStr =result.text;
        
    }else{
        self.rsultStr =@"";

    }
//    if ([self.delegate respondsToSelector:@selector(wXSpeech:wXInfo:)]) {
//        [self.delegate wXSpeech:self wXInfo:self.rsultStr];
//    }
//    [[WXVoiceSDK sharedWXVoice]cancel];
}
- (void)voiceInputMakeError:(NSInteger)errorCode{
    NSLog(@"%ld",(long)errorCode);
    
    NSString *errorStr=nil;
    switch (errorCode) {
        case WXErrorOfSuccess:
            errorStr =@"识别成功";
            NSLog(@"识别成功");
            break;
        case WXErrorOfNoNetWork:
            errorStr =@"没有网络";
            NSLog(@"没有网络");
            break;
        case WXErrorOfTimeOut:
            errorStr =@"网络超时";
            NSLog(@"网络超时");
            break;
        case WXErrorOfQuotaExhaust:
            errorStr =@"AppID配额用完";
            NSLog(@"AppID配额用完");
            break;
        case WXErrorOfAppIDError:
            errorStr =@"AppID错误";
            NSLog(@"AppID错误");
            break;
        case WXVoiceRecoErrorOfNoSound:
            errorStr =@"没有获取到录音";
            NSLog(@"没有获取到录音");
            break;
        case WXVoiceRecoErrorOfVoiceTooLarge:
            errorStr =@"录音过长";
            NSLog(@"录音过长");
            break;
        case WXVoiceRecoErrorOfRecord:
            errorStr =@"没有录音设备";
            NSLog(@"没有录音设备");
            break;
        case WXVoiceRecoErrorOfCannotUseMic:
            errorStr =@"无法使用mic";
            NSLog(@"无法使用mic");
            break;
            
        default:
            break;
    }
//    if ([self.delegate respondsToSelector:@selector(wXSpeech:wXInfo:)]) {
//        [self.delegate wXSpeech:self wXInfo:errorStr];
//    }
    [self showHUD:errorStr];
}

- (void)voiceInputWaitForResult{
    [[WXVoiceSDK sharedWXVoice] stopContinusMode];
    NSLog(@"-------------call back voiceInputWaitForResult----------------");
}
- (void)voiceInputDidCancel{
}


-(void)startRecord{
     [[WXVoiceSDK sharedWXVoice]startContinusMode];
}
-(void)finishRecorder1{
    [[WXVoiceSDK sharedWXVoice]stopContinusMode];
    
    if (self.rsultStr.length!=0) {
        if ([self.delegate respondsToSelector:@selector(wXSpeech:wXInfo:)]) {
            [self.delegate wXSpeech:self wXInfo:self.rsultStr];
        }

    }
    
    
}

-(void)initRecognizer{
    
    // SDK
    WXVoiceSDK *speechRecognizer = [WXVoiceSDK sharedWXVoice];
    //可选设置
    speechRecognizer.silTime = 10.5f;
    //必选设置
    speechRecognizer.delegate = self;
    [speechRecognizer setAppID:@"wx725aa31f5a2da818"];
    
    [speechRecognizer setDomain:10];
    //[speechRecognizer setContinuousMode:true];
    //[speechRecognizer setMaxResultCount:3];
    
}


/**
 *  显示文字HUD
 *
 *  @param str 显示的文字
 */
-(void)showHUD:(NSString*)str
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:str preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了按钮1，进入按钮1的事件");
    }];
    [alertController addAction:action1];
    [[self getCurrentVC] presentViewController:alertController animated:YES completion:nil];
}

#pragma mark 获取当前的控制器
- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

@end
